//
//  CNBBSPostedViewController.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/6/4.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNBBSPostedViewController.h"
#import "CNComposeToolbar.h"
#import "CNBBSPostedScoreViewController.h"
#import "CNBBSPostedSecionViewController.h"
#import "CNBBSFavoriteViewModel.h"
#import <HXPhotoPicker/HXPhotoPicker.h>
#import <FDFullscreenPopGesture/UINavigationController+FDFullscreenPopGesture.h>
#import <IQKeyboardManager/IQKeyboardManager.h>
@interface CNBBSPostedViewController ()<CNComposeToolbarDelegate,HXPhotoViewDelegate,UIImagePickerControllerDelegate,UITextViewDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>
{
    BOOL _wasKeyboardManagerEnabled;
}

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UITextField *titleTextField;

@property (nonatomic, strong) PPStickerTextView *inputTextView;

@property (nonatomic, strong) CNComposeToolbar *composeToolbar;

@property (nonatomic, strong) UIButton *selectSectionBtn;

@property (nonatomic, strong) UILabel *sectionLabel;

@property (strong, nonatomic) HXPhotoManager *manager;
@property (strong, nonatomic) HXPhotoView *photoView;
@property (strong, nonatomic) HXDatePhotoToolManager *toolManager;

@property (nonatomic, assign) BOOL keepsPreModeTextViewWillEdited;

@property (nonatomic, copy) NSString *plainText;

@property (nonatomic, copy) NSString *forumId;

@property (nonatomic, assign) BOOL techForum;

@property (nonatomic, copy) NSString *forumName;

@property (nonatomic, copy) NSString *score;

@property (nonatomic, strong) NSArray *picImageArray;

@property (nonatomic, strong) NSArray *picTypeArray;

@property (nonatomic, strong) CNBBSFavoriteViewModel *postedVM;

@property (nonatomic, strong) CNBBSFavoriteViewModel *uploadPicVM;

@property (nonatomic, strong) UIButton *releaseBtn;

@end

@implementation CNBBSPostedViewController

-(CNBBSFavoriteViewModel *)postedVM
{
    if (!_postedVM) {
        _postedVM = [[CNBBSFavoriteViewModel alloc]init];
    }
    return _postedVM;
}

-(CNBBSFavoriteViewModel *)uploadPicVM
{
    if (!_uploadPicVM) {
        _uploadPicVM = [[CNBBSFavoriteViewModel alloc]init];
    }
    return _uploadPicVM;
}

-(UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.theme_backgroundColor = pageBGColorPicker;
        [self.view addSubview:_contentView];
        [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(self.view);
//            make.bottom.mas_equalTo(-48);
            if (@available(iOS 11.0,*)) {
                make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_equalTo(-48);
            }
            else
            {
                make.bottom.mas_equalTo(-48);
            }
        }];
    }
    return _contentView;
}

-(UITextField *)titleTextField
{
    if (!_titleTextField)
    {
        _titleTextField = [[UITextField alloc]init];
        _titleTextField.theme_backgroundColor = pageBGColorPicker;
        _titleTextField.placeholder = @"添加标题";
        _titleTextField.theme_placeholderAttributes = [ThemeDictionaryPicker pickerWithDicts:@[@{NSForegroundColorAttributeName: commentPlaceholderTextColor,NSFontAttributeName:[UIFont systemFontOfSize:17]},@{NSForegroundColorAttributeName: commentPlaceholderNightTextColor,NSFontAttributeName:[UIFont systemFontOfSize:17]}]];
        _titleTextField.font = [UIFont systemFontOfSize:17];
        _titleTextField.autocorrectionType = UITextAutocorrectionTypeNo; //关闭自动纠错
        _titleTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; //关闭首字母大写
        _titleTextField.theme_textColor = cellTitleTextColorPicker;
//        _titleTextField.theme_tintColor = cellTitleTextColorPicker;
        _titleTextField.keyboardAppearance = [CNThemesManager isNight] ? UIKeyboardAppearanceDark : UIKeyboardAppearanceDefault;
        _titleTextField.delegate = self;
        [self.contentView addSubview:_titleTextField];
        [_titleTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(12);
            make.right.mas_equalTo(-12);
            make.height.mas_equalTo(48);
        }];
    }
    return _titleTextField;
}

-(PPStickerTextView *)inputTextView
{
    if (!_inputTextView) {
        _inputTextView = [[PPStickerTextView alloc]init];
        _inputTextView.theme_backgroundColor = pageBGColorPicker;
        _inputTextView.textContainerInset = UIEdgeInsetsMake(0,-5, 0, 0);
        _inputTextView.delegate = self;
        _inputTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
        _inputTextView.keyboardAppearance = [CNThemesManager isNight] ? UIKeyboardAppearanceDark : UIKeyboardAppearanceDefault;
        _inputTextView.showsVerticalScrollIndicator = YES;
        if ([CNThemesManager isNight])
        {
            _inputTextView.placeholderColor = commentPlaceholderNightTextColor;
            
        }
        else
        {
            _inputTextView.placeholderColor = commentPlaceholderTextColor;
        }
        _inputTextView.theme_textColor = cellTitleTextColorPicker;
        _inputTextView.placeholder = @"添加内容";
        _inputTextView.scrollsToTop = NO;
        _inputTextView.returnKeyType = UIReturnKeyDefault;
        _inputTextView.enablesReturnKeyAutomatically = YES;
        if (@available(iOS 11.0, *)) {
            _inputTextView.textDragInteraction.enabled = NO;
        }
        _inputTextView.font = [UIFont systemFontOfSize:14];
        @weakify(self);
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(inputTextViewDidClick)];
        tapGesture.delegate = self;
        [_inputTextView addGestureRecognizer:tapGesture];
//        [_inputTextView addTapGestureWithBlock:^(UIView *gestureView) {
//            @strongify(self);
//            self.inputTextView.inputView = nil;
//            [self.inputTextView reloadInputViews];
//            [self.inputTextView becomeFirstResponder];
//        }];
//        _inputTextView.theme_tintColor = cellTitleTextColorPicker;
        [self.contentView addSubview:_inputTextView];
        [_inputTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.titleTextField);
            make.top.mas_equalTo(self.titleTextField.mas_bottom).mas_equalTo(0);
            make.right.mas_equalTo(self.titleTextField);
            make.bottom.mas_lessThanOrEqualTo(self.photoView.mas_top).mas_offset(-29);
        }];
    }
    return _inputTextView;
}

- (HXPhotoView *)photoView {
    if (!_photoView) {
        _photoView = [[HXPhotoView alloc] initWithFrame:CGRectZero manager:self.manager];
        _photoView.theme_backgroundColor = pageBGColorPicker;
        _photoView.delegate = self;
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        // 设置UICollectionView为横向滚动
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        // 每一行cell之间的间距
        flowLayout.minimumLineSpacing = 0;
        // 每一列cell之间的间距
        // flowLayout.minimumInteritemSpacing = 10;
        // 设置第一个cell和最后一个cell,与父控件之间的间距
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 12, 0, 12);
        flowLayout.minimumLineSpacing = 8;// 根据需要编写
        flowLayout.minimumInteritemSpacing = 8;// 根据需要编写
        if (DEVICE_IS_IPHONE4 || DEVICE_IS_IPHONE5)
        {
            flowLayout.itemSize = CGSizeMake(50, 50);// 该行代码就算不写,item也会有默认尺寸
        }
        else
        {
            flowLayout.itemSize = CGSizeMake(96, 96);// 该行代码就算不写,item也会有默认尺寸
        }
        
        _photoView.collectionView.collectionViewLayout = flowLayout;
        _photoView.collectionView.scrollEnabled = YES;
        [self.contentView addSubview:_photoView];
        [_photoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.top.mas_lessThanOrEqualTo(self.inputTextView.mas_bottom).mas_offset(29);
            make.height.mas_equalTo(1);
            make.bottom.mas_equalTo(self.selectSectionBtn.mas_top).mas_equalTo(0);
        }];
    }
    return _photoView;
}

-(UIButton *)selectSectionBtn
{
    if (!_selectSectionBtn) {
        _selectSectionBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _selectSectionBtn.theme_backgroundColor = pageBGColorPicker;
        [self.contentView addSubview:_selectSectionBtn];
        [_selectSectionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(44);
            make.bottom.mas_equalTo(0);
        }];
        @weakify(self);
        [_selectSectionBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            
            CNBBSPostedSecionViewController *sectionVC = [[CNBBSPostedSecionViewController alloc]init];
            sectionVC.sectionBlock = ^(NSString *forumName, NSString *forumId, BOOL techForum) {
                self.sectionLabel.text = forumName;
                self.forumId = forumId;
                self.techForum = techForum;
                self.forumName = forumName;
            };
            [self.navigationController pushViewController:sectionVC animated:YES];
            
        } forControlEvents:(UIControlEventTouchUpInside)];
        
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"bbsSection"];
        [_selectSectionBtn addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(12);
            make.centerY.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(16, 16));
        }];
        
        self.sectionLabel = [[UILabel alloc]init];
        _sectionLabel.theme_textColor = cellTitleTextColorPicker;
        _sectionLabel.text = @"发布到哪个版块";
        _sectionLabel.font = [UIFont systemFontOfSize:14];
        [_selectSectionBtn addSubview:_sectionLabel];
        [_sectionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(imageView.mas_right).mas_equalTo(5);
            make.centerY.mas_equalTo(0);
        }];
        
        UIImageView *rightImageView = [[UIImageView alloc]init];
        rightImageView.theme_image = arrowRightImage;
        [_selectSectionBtn addSubview:rightImageView];
        [rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-12);
            make.centerY.mas_equalTo(0);
            make.size.mas_equalTo(CGSizeMake(8, 16));
            make.left.mas_equalTo(self.sectionLabel.mas_right).mas_equalTo(20);
        }];
        
    }
    return _selectSectionBtn;
}


-(CNComposeToolbar *)composeToolbar
{
    if (!_composeToolbar) {
        _composeToolbar = [[CNComposeToolbar alloc]init];
        _composeToolbar.theme_backgroundColor = menuPageBGColorPicker;
        [self.view addSubview:_composeToolbar];
        [_composeToolbar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(48);
            if (@available(iOS 11.0,*)) {
                make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            }
            else
            {
                make.bottom.mas_equalTo(0);
            }
        }];
        _composeToolbar.delegate = self;
        _composeToolbar.textView = self.inputTextView;
    }
    return _composeToolbar;
}

- (HXDatePhotoToolManager *)toolManager {
    if (!_toolManager) {
        _toolManager = [[HXDatePhotoToolManager alloc] init];
    }
    return _toolManager;
}

- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.navigationBar = ^(UINavigationBar *navigationBar, UIViewController *viewController) {
            
            navigationBar.barTintColor = [CNThemesManager isNight] ? slideBarNightTextColor : slideBarTextColor;
            navigationBar.tintColor = [CNThemesManager isNight] ? navigationBarNightTitleColor: navigationBarTitleColor;
            navigationBar.theme_titleTextAttributes = [ThemeStringAttributesPicker pickerWithAttributes:@[@{NSForegroundColorAttributeName: navigationBarTitleColor},@{NSForegroundColorAttributeName: navigationBarNightTitleColor}]];
//                navigationBar.translucent = NO;
        };
        _manager.configuration.creationDateSort = NO;
        _manager.configuration.openCamera = YES;
        _manager.configuration.lookLivePhoto = NO;
        _manager.configuration.photoMaxNum = 6;
        _manager.configuration.videoMaxNum = 6;
        _manager.configuration.maxNum = 6;
        _manager.configuration.videoMaximumDuration = 500.f;
        _manager.configuration.hideOriginalBtn = YES;
        _manager.configuration.saveSystemAblum = NO;
        //        _manager.configuration.reverseDate = YES;
        _manager.configuration.showDateSectionHeader = NO;
        _manager.configuration.selectTogether = NO;
        _manager.configuration.navigationTitleSynchColor = NO;
        _manager.configuration.themeColor = cellDesTitleTextColor;
        //_manager.configuration.navBarBackgroudColor = slideBarTextColor;
        _manager.configuration.cellSelectedBgColor = naviBGColor;
        _manager.configuration.originalNormalImageName = @"photo_original_noselect";
        _manager.configuration.originalSelectedImageName = @"photo_original_select";
        _manager.configuration.navigationTitleColor = [CNThemesManager isNight] ? navigationBarNightTitleColor: navigationBarTitleColor;
        _manager.configuration.statusBarStyle = [CNThemesManager isNight] ? UIStatusBarStyleLightContent : UIStatusBarStyleDefault;
        _manager.configuration.photoListBottomView = ^(HXPhotoBottomView *bottomView) {
            bottomView.backgroundColor = [CNThemesManager isNight] ? slideBarNightTextColor : slideBarTextColor;
            bottomView.bgView.alpha = 0.0;
//            UIView *lineView = [[UIView alloc]init];
//            lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//            [bottomView addSubview:lineView];
//            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.top.left.right.mas_equalTo(0);
//                make.height.mas_equalTo(0.5);
//            }];
        };
        _manager.configuration.changeAlbumListContentView = NO;
        _manager.configuration.photoListCollectionView = ^(UICollectionView *collectionView) {
            collectionView.theme_backgroundColor = pageBGColorPicker;
        };
        _manager.configuration.albumListTableView = ^(UITableView *tableView) {
            tableView.theme_backgroundColor = pageBGColorPicker;
        };
        _manager.configuration.albumListCollectionView = ^(UICollectionView *collectionView) {
            collectionView.theme_backgroundColor = pageBGColorPicker;
        };
        _manager.configuration.previewCollectionView = ^(UICollectionView *collectionView) {
            collectionView.theme_backgroundColor = pageBGColorPicker;
        };
        _manager.configuration.previewBottomView = ^(HXPhotoPreviewBottomView *bottomView) {
            bottomView.backgroundColor = [CNThemesManager isNight] ? slideBarNightTextColor : slideBarTextColor;
            bottomView.bgView.alpha = 0.0;
//            UIView *lineView = [[UIView alloc]init];
//            lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//            [bottomView addSubview:lineView];
//            [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//                make.top.left.right.mas_equalTo(0);
//                make.height.mas_equalTo(0.5);
//            }];
        };
        _manager.configuration.sectionHeaderSuspensionBgColor = [CNThemesManager isNight] ? slideBarTextColor : navigationBarTitleColor;
        _manager.configuration.sectionHeaderSuspensionTitleColor = [CNThemesManager isNight] ? navigationBarNightTitleColor : navigationBarTitleColor;
        _manager.configuration.cameraCellShowPreview = NO;
        //        _manager.configuration.rowCount = 3;
        //        _manager.configuration.movableCropBox = YES;
        //        _manager.configuration.movableCropBoxEditSize = YES;
        //        _manager.configuration.movableCropBoxCustomRatio = CGPointMake(1, 1);
        
        __weak typeof(self) weakSelf = self;
        //        _manager.configuration.replaceCameraViewController = YES;
        _manager.configuration.shouldUseCamera = ^(UIViewController *viewController, HXPhotoConfigurationCameraType cameraType, HXPhotoManager *manager) {
            
            // 这里拿使用系统相机做例子
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = (id)weakSelf;
            imagePickerController.allowsEditing = NO;
            NSString *requiredMediaTypeImage = ( NSString *)kUTTypeImage;
            NSString *requiredMediaTypeMovie = ( NSString *)kUTTypeMovie;
            NSArray *arrMediaTypes;
            if (cameraType == HXPhotoConfigurationCameraTypePhoto) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage,nil];
            }else if (cameraType == HXPhotoConfigurationCameraTypeVideo) {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeMovie,nil];
            }else {
                arrMediaTypes=[NSArray arrayWithObjects:requiredMediaTypeImage, requiredMediaTypeMovie,nil];
            }
            [imagePickerController setMediaTypes:arrMediaTypes];
            // 设置录制视频的质量
            [imagePickerController setVideoQuality:UIImagePickerControllerQualityTypeHigh];
            //设置最长摄像时间
            [imagePickerController setVideoMaximumDuration:60.f];
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePickerController.navigationController.navigationBar.tintColor = [UIColor whiteColor];
            imagePickerController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            [viewController presentViewController:imagePickerController animated:YES completion:nil];
        };
    }
    return _manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //禁止侧滑
    self.fd_interactivePopDisabled = YES;
    self.view.theme_backgroundColor = pageBGColorPicker;
    self.selectSectionBtn.hidden = NO;
    self.photoView.hidden = YES;
    self.composeToolbar.hidden = NO;
    self.title = @"发帖";
    [self addBlackItemToVC];
    [self addReleaseToVC];
//    if ([CNThemesManager isNight])
//    {
//        //切换背景为夜间颜色
//        [self wr_setNavBarBarTintColor:slideBarNightTextColor];
//        [self wr_setNavBarTitleColor:navigationBarNightTitleColor];
//        [self wr_setStatusBarStyle:UIStatusBarStyleLightContent];
//    }
//    else
//    {
//        //切换背景为白天颜色
//        [self wr_setNavBarBarTintColor:slideBarTextColor];
//        [self wr_setNavBarTitleColor:navigationBarTitleColor];
//        [self wr_setStatusBarStyle:UIStatusBarStyleDefault];
//    }
    //添加分割线
//    UIView *lineView = [[UIView alloc]init];
//    lineView.theme_backgroundColor = bbsSectionLineColorPicker;
//    [self.view addSubview:lineView];
//    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.mas_equalTo(0);
//        make.top.mas_equalTo(0);
//        make.height.mas_equalTo(0.5);
//    }];
//    lineView.layer.zPosition = 10;
  
    // 监听键盘
    // 键盘的frame(位置)即将改变, 就会发出UIKeyboardWillChangeFrameNotification
    // 键盘即将弹出, 就会发出UIKeyboardWillShowNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘即将隐藏, 就会发出UIKeyboardWillHideNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.titleTextField becomeFirstResponder];
    
    //添加页面监控
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _wasKeyboardManagerEnabled = [[IQKeyboardManager sharedManager] isEnabled];
    [[IQKeyboardManager sharedManager] setEnable:NO];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:YES]; 
    [[IQKeyboardManager sharedManager] setEnable:_wasKeyboardManagerEnabled];
    
}

- (void)addBlackItemToVC
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn theme_setImage:naviCleanImage forState:UIControlStateNormal]; //设置自定义返回图片
    [backBtn theme_setImage:naviCleanImage forState:UIControlStateHighlighted]; //设置自定义返回图片
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -20, 0, 0)];  //调整按钮内图片的布局
    [backBtn setEnlargeEdge:15];
    backBtn.frame = CGRectMake(0, 0, 30, 44);
    @weakify(self);
    [backBtn bk_addEventHandler:^(id sender) {
        
        @strongify(self);
        [self.navigationController popViewControllerAnimated:YES];
    } forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    //使用弹簧控件缩小菜单按钮和边缘距离
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    UIBarButtonItem *spaceItemRight = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    //spaceItem.width = -12;
    //spaceItemRight.width = 40;
    self.navigationItem.leftBarButtonItems = @[spaceItem,menuItem,spaceItemRight];
}

#pragma mark - 添加发布按钮
- (void)addReleaseToVC
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.releaseBtn = btn;
    [btn setTitle:@"发布" forState:(UIControlStateNormal)];
    [btn theme_setTitleColor:linkAddBtnTextColorPicker forState:(UIControlStateNormal)];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:16 weight:(UIFontWeightRegular)]];
    btn.userInteractionEnabled = NO;
    @weakify(self);
    [btn bk_addEventHandler:^(id sender) {
        @strongify(self);
        [self postedTopic];
    } forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
    //使用弹簧控件缩小菜单按钮和边缘距离
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    UIBarButtonItem *spaceItemRight = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    spaceItem.width =  kIOS11_OR_LATER ? 0 : -10;
    if (kIOS11_OR_LATER) {
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0,0, -8);
        btn.hitScale = 3;
    }
    else
    {
        [btn sizeToFit];
    }
    spaceItemRight.width = 0;
    self.navigationItem.rightBarButtonItems = @[spaceItem,menuItem];
}

#pragma mark - 发帖请求

-(void)postedTopic
{

    
    [self.titleTextField resignFirstResponder];
    [self.inputTextView resignFirstResponder];
    NSString *titleText = [self.titleTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *contentText = [self.inputTextView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSUInteger titileNum =  titleText.length;
    NSUInteger contentNum =  contentText.length;
    
    if(titileNum < 1 || titileNum > 80)
    {
        [CSDNTool showAlert:@"标题字数应在1-80之间" inView:self.view];
        return ;
    }
    
    if(contentNum < 10)
    {
        [CSDNTool showAlert:@"内容字数应在大于10" inView:self.view];
        return ;
    }
    if (self.forumId == nil  || [self.forumId isEqualToString:@""])
    {
        [CSDNTool showAlert:@"请选择版块" inView:self.view];
        return;
    }
    if (self.score == nil  || [self.score isEqualToString:@""])
    {
        [CSDNTool showAlert:@"请选择积分" inView:self.view];
        return;
    }
    self.releaseBtn.userInteractionEnabled = NO;

    //正在加载视图
    [MBProgressHUD showMessage:@"正在发布,请稍后..." toView:self.view];
    
    __block NSString * imageStr = @"";
    NSMutableArray *tagArray = [[NSMutableArray alloc]init];
    
    // 创建队列组，可以使多个网络请求异步执行，执行完之后再进行操作
    dispatch_group_t group = dispatch_group_create();
    //创建全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

    dispatch_group_async(group, queue, ^{
        // 循环上传数据
        for (int i = 0; i < self.picImageArray.count; i++)
        {
            //创建dispatch_semaphore_t对象
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            [self.uploadPicVM getBBSUpLoadPicWithImageArray:@[self.picImageArray[i]] AndImageTypes:@[self.picTypeArray[i]] CompletionHandle:^(NSError *error) {
                
                if (!error)
                {
                    if (self.uploadPicVM.code == 200)
                    {
                        imageStr = [NSString stringWithFormat:@"%@[img=%@][/img]",imageStr,self.uploadPicVM.url];
                        [tagArray addObject:[NSNumber numberWithBool:YES]];
                    }
                }
                 dispatch_semaphore_signal(semaphore);
            }];
            
            //信号量减1，如果>0，则向下执行，否则等待
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
    });
    
    
    NSString *title = self.titleTextField.text;
    // 当所有队列执行完成之后
    
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 执行下面的判断代码
        if (tagArray.count == self.picImageArray.count)
        {
            [self.postedVM getBBSPostedWithTitle:title AndBody:[[CSDNTool replacingSpaceWithText:[PPStickerDataManager changeStringWithUrl:self.plainText]] stringByAppendingString:imageStr] AndForumId:self.forumId AndPoint:self.score CompletionHandle:^(NSError *error) {
                self.releaseBtn.userInteractionEnabled = YES;
                if (!error)
                {
                    //隐藏加载视图
                    [MBProgressHUD hideHUDForView:self.view];
                    if (self.postedVM.code == 200)
                    {
                        [CSDNTool showImageAlert:@"发帖成功" inView:self.view];
                        @weakify(self);
                        [self bk_performBlock:^(id obj) {
                            @strongify(self);
                            [self.navigationController popViewControllerAnimated:YES];
                        } afterDelay:1.0];
                                                
                    }else if (self.postedVM.code == 401){
                        [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
                    }else{
                        [self showErrorMsg:self.postedVM.message];
                    }
                }
                else
                {
                    //隐藏加载视图
                    [MBProgressHUD hideHUDForView:self.view];
                    [self showErrorMsgDescription:error.userInfo[NSLocalizedDescriptionKey]?:@"发帖失败"];
                }
            }];
        }
        else
        {

            dispatch_async(dispatch_get_main_queue(), ^{
                //隐藏加载视图

               [MBProgressHUD hideHUDForView:self.view];
               [self showErrorMsgDescription:@"您有图片尚未上传成功，请稍候再试"];
            });
        }
        
    });
    
}

#pragma mark - 键盘通知

/*
 *  响应通知
 */
-(void)keyboardWillShow:(NSNotification *)noti
{
    //self.composeToolbar.hidden = NO;
    // 1.键盘弹出需要的时间
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 2.动画
    [UIView animateWithDuration:duration animations:^{
        // 取出键盘高度
        CGRect keyboardF = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat keyboardH = keyboardF.size.height;
        if (iPhoneX)
        {
            keyboardH = keyboardH - 34;
        }
        self.composeToolbar.transform = CGAffineTransformMakeTranslation(0, - keyboardH);
        [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.bottom.mas_equalTo(- keyboardH-48);
            if (@available(iOS 11.0,*)) {
                make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_equalTo(-(keyboardH+48));
            }
            else
            {
                make.bottom.mas_equalTo(-(keyboardH+48));
            }
        }];
        [self.view layoutIfNeeded];
    }];
    
}


/*
 *  键盘即将退下
 */
-(void)keyboardWillHide:(NSNotification *)noti
{
    // 1.键盘弹出需要的时间
    CGFloat duration = [noti.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 2.动画
    // 2.动画
    [UIView animateWithDuration:duration animations:^{
        self.composeToolbar.transform = CGAffineTransformIdentity;//回复之前的位置
        [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
        }];
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_equalTo(self.view);
            if (@available(iOS 11.0,*)) {
                make.bottom.mas_equalTo(self.view).mas_equalTo(-48);
            }
            else
            {
                make.bottom.mas_equalTo(-48);
            }
        }];
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    HXPhotoModel *model;
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        model = [HXPhotoModel photoModelWithImage:image];
        if (self.manager.configuration.saveSystemAblum) {
            [HXPhotoTools savePhotoToCustomAlbumWithName:self.manager.configuration.customAlbumName photo:model.thumbPhoto];
        }
    }else  if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        NSURL *url = info[UIImagePickerControllerMediaURL];
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]
                                                         forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
        float second = 0;
        second = urlAsset.duration.value/urlAsset.duration.timescale;
        model = [HXPhotoModel photoModelWithVideoURL:url videoTime:second];
        if (self.manager.configuration.saveSystemAblum) {
            [HXPhotoTools saveVideoToCustomAlbumWithName:self.manager.configuration.customAlbumName videoURL:url];
        }
    }
    if (self.manager.configuration.useCameraComplete) {
        self.manager.configuration.useCameraComplete(model);
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - HXPhotoViewDelegate

- (void)photoView:(HXPhotoView *)photoView changeComplete:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photos videos:(NSArray<HXPhotoModel *> *)videos original:(BOOL)isOriginal {
    
    if (allList.count > 0)
    {
        self.photoView.hidden = NO;
        [_photoView mas_updateConstraints:^(MASConstraintMaker *make) {
           
            if (DEVICE_IS_IPHONE4 || DEVICE_IS_IPHONE5)
            {
                make.height.mas_equalTo(50);
            }
            else
            {
                make.height.mas_equalTo(96);
            }
        }];
    }
    else
    {
        self.photoView.hidden = YES;
        [_photoView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(1);
        }];
    }
    
    NSSLog(@"所有:%ld - 照片:%ld - 视频:%ld",allList.count,photos.count,videos.count);
    NSSLog(@"所有:%@ - 照片:%@ - 视频:%@",allList,photos,videos);
    
    [self.toolManager getSelectedImageDataList:allList success:^(NSArray<NSData *> *imageDataList) {
        self.picImageArray = imageDataList;
    } failed:^{
        
    }];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *types = [[NSMutableArray alloc]init];
        for (HXPhotoModel *model in allList)
        {
            if (model.type == HXPhotoModelMediaTypePhotoGif)
            {
                [types addObject:@"gif"];
            }
            else
            {
                [types addObject:@"png"];
            }
        }
        self.picTypeArray = [types copy];
    });

}

- (void)photoView:(HXPhotoView *)photoView deleteNetworkPhoto:(NSString *)networkPhotoUrl {
    NSSLog(@"%@",networkPhotoUrl);
}


- (void)photoView:(HXPhotoView *)photoView currentDeleteModel:(HXPhotoModel *)model currentIndex:(NSInteger)index {
    NSSLog(@"%@ --> index - %ld",model,index);
}


#pragma mark CNComposeToolbarDelegate

-(void)composeToolbarDidClickSendButton:(CNComposeToolbar *)inputView
{
    [inputView.textView resignFirstResponder];
}

-(void)composeToolbar:(CNComposeToolbar *)toolbar didClickButton:(CNComposeToolbarButtonType)buttonType
{
    switch (buttonType) {
        case CNComposeToolbarButtonTypeScore:
            [self clickScoreButton];
            break;
        case CNComposeToolbarButtonTypeEmotion:
            
            break;
        case CNComposeToolbarButtonTypePicture:
            [self clickPictureButton];
            break;
            
        default:
            break;
    }
}

- (void)clickPictureButton
{
    [self.photoView goPhotoViewController];
}

- (void)clickScoreButton
{
    [self.titleTextField resignFirstResponder];
    [self.inputTextView resignFirstResponder];
    if (self.forumId == nil  || [self.forumId isEqualToString:@""] || self.forumName == nil  || [self.forumName isEqualToString:@""])
    {
        [CSDNTool showAlert:@"请先选择版块" inView:self.view];
    }
    else
    {
        CNBBSPostedScoreViewController *scoreVC = [[CNBBSPostedScoreViewController alloc]init];
        scoreVC.techForum = self.techForum;
        scoreVC.scoreBlock = ^(NSString *score) {
            self.score = score;
            NSMutableAttributedString *scoreStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"给分数 %@",score]];
            scoreStr.yy_font = [UIFont systemFontOfSize:13];
            scoreStr.yy_color = scoreTextColor;
            [scoreStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0,3)];
            [scoreStr addAttribute:NSForegroundColorAttributeName value:[CNThemesManager isNight] ? cellComNightTitleTextColor :cellComTitleTextColor range:NSMakeRange(0,3)];
            self.composeToolbar.scoreStr = scoreStr;
        };
        [self.navigationController pushViewController:scoreVC animated:YES];
    }
}

#pragma mark - TextFieldDelegate

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self.composeToolbar.pictureButton theme_setImage:togglePictureNoImage forState:UIControlStateNormal];
    [self.composeToolbar.pictureButton theme_setImage:togglePictureNoImage forState:UIControlStateHighlighted];
    [self.composeToolbar.emojiToggleButton theme_setImage:toggleEmojiNoImage forState:UIControlStateNormal];
    [self.composeToolbar.emojiToggleButton theme_setImage:toggleEmojiNoImage forState:UIControlStateHighlighted];
    self.composeToolbar.emojiToggleButton.userInteractionEnabled = NO;
    self.composeToolbar.pictureButton.userInteractionEnabled = NO;
}

#pragma TextViewDelegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.keepsPreModeTextViewWillEdited = NO;
    [self.composeToolbar.pictureButton theme_setImage:togglePictureImage forState:UIControlStateNormal];
    [self.composeToolbar.pictureButton theme_setImage:togglePictureImage forState:UIControlStateHighlighted];
    [self.composeToolbar.emojiToggleButton theme_setImage:toggleEmojiImage forState:UIControlStateNormal];
    [self.composeToolbar.emojiToggleButton theme_setImage:toggleEmojiImage forState:UIControlStateHighlighted];
    self.composeToolbar.emojiToggleButton.userInteractionEnabled = YES;
    self.composeToolbar.pictureButton.userInteractionEnabled = YES;
    return YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.keepsPreModeTextViewWillEdited = YES;
    //重置键盘
    self.inputTextView.inputView = nil;
    self.composeToolbar.selectedButton = nil;
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    
}

- (void)textViewDidChange:(UITextView *)textView
{
    [textView.superview layoutSubviews];
    [self refreshTextUI];
    
    [self.inputTextView scrollRangeToVisible:self.inputTextView.selectedRange];
    NSString *text = [textView.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (text.length > 0)
    {
        [self.releaseBtn theme_setTitleColor:naviButtonTextColorPicker forState:(UIControlStateNormal)];
        self.releaseBtn.userInteractionEnabled = YES;
    }
    else
    {
        [self.releaseBtn theme_setTitleColor:linkAddBtnTextColorPicker forState:(UIControlStateNormal)];
        self.releaseBtn.userInteractionEnabled = NO;
    }
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}

#pragma mark - private method

- (void)refreshTextUI
{
    if (!self.inputTextView.text.length) {
        return;
    }
    
    UITextRange *markedTextRange = [self.inputTextView markedTextRange];
    UITextPosition *position = [self.inputTextView positionFromPosition:markedTextRange.start offset:0];
    if (position) {
        return;     // 正处于输入拼音还未点确定的中间状态
    }
    
    NSRange selectedRange = self.inputTextView.selectedRange;
    NSMutableAttributedString *attributedComment = [[NSMutableAttributedString alloc] initWithString:self.plainText attributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:15], NSForegroundColorAttributeName: [CNThemesManager isNight] ? cellComNightTitleTextColor :cellComTitleTextColor }];
    
    // 匹配表情
    [PPStickerDataManager.sharedInstance replaceEmojiForAttributedString:attributedComment font:[UIFont systemFontOfSize:15]];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 6;
    [attributedComment addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:attributedComment.pp_rangeOfAll];
    
    NSUInteger offset = self.inputTextView.attributedText.length - attributedComment.length;
    self.inputTextView.attributedText = attributedComment;
    self.inputTextView.selectedRange = NSMakeRange(selectedRange.location - offset, 0);
}

- (NSString *)plainText
{
    return [self.inputTextView.attributedText pp_plainTextForRange:NSMakeRange(0, self.inputTextView.attributedText.length)];
}
#pragma mark -gesture
- (void)inputTextViewDidClick{
   self.inputTextView.inputView = nil;
    [self.inputTextView reloadInputViews];
    self.composeToolbar.selectedButton = nil;
    [self.inputTextView becomeFirstResponder];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}
-(void)dealloc
{
    //在页面消失的回调方法中移除通知。
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
